<script setup lang="ts">
import {onBeforeUpdate, reactive, ref} from "vue";
import {serialStore} from "../../store";
import {storeToRefs} from "pinia";

const store = serialStore()
const storeRef = storeToRefs(store)

const dialog = ref(false)
const serial = ref()
const baudRate = ref()
const dataBits = ref()
const stopBits = ref()
const parity = ref()

onBeforeUpdate(() => {
    serial.value = storeRef.serial.value
    baudRate.value = storeRef.baud.value
    dataBits.value = storeRef.data.value
    stopBits.value = storeRef.stop.value
    parity.value = storeRef.parity.value
})

const form = reactive({
    serial: {
        label: '串口号',
        placeholder: '请选择串口',
        current: serial,
        list: storeRef.serialPort
    },
    baud: {
        label: '波特率',
        placeholder: '请选择波特率',
        current: baudRate,
        list: storeRef.baudRate
    },
    data: {
        label: '数据位',
        placeholder: '请选择数据位',
        current: dataBits,
        list: storeRef.dataBits
    },
    parity: {
        label: '校验位',
        placeholder: '请选择校验位',
        current: parity,
        list: storeRef.parityBits
    },
    stop: {
        label: '停止位',
        placeholder: '请选择停止位',
        current: stopBits,
        list: storeRef.stopBits
    },
})


const openDialog = () => {
    dialog.value = true
}

const confirmForm = () => {
    dialog.value = false
    storeRef.serial.value = serial.value
    storeRef.baud.value = baudRate.value
    storeRef.data.value = dataBits.value
    storeRef.stop.value = stopBits.value
    storeRef.parity.value = parity.value
}
defineExpose({openDialog})

</script>

<template>
    <el-dialog v-model="dialog" title="串口配置" width="400">
        <el-form :model="form">
            <el-form-item :label="item.label" label-width="auto" v-for="item in form">
                <el-select v-model="item.current" :placeholder="item.placeholder">
                    <el-option :label="it" :value="it" v-for="it in item.list" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog = false">Cancel</el-button>
                <el-button type="primary" @click="confirmForm">
                    Confirm
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>

</style>